﻿using App.Extension;
using NLog;
using Simple.BasicNet.Core;
using Simple.BasicNet.Core.Handle;
using Simple.BasicNet.Core.Net;
using Simple.Framework.Ioc;
using Simple.PrettyNet;
using Simple.PrettyNet.Handle;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Metadata;
using System.Text;
using System.Threading.Tasks;

/*********************************************************
 * 命名空间 App.MessageExtension
 * 接口名称 IDTMessage
 * 开发人员：11920
 * 创建时间：2023/4/14 14:19:31
 * 描述说明：
 * 更改历史：
 * 
 * *******************************************************/
namespace App.MessageExtension
{
	internal class IDTMessageHandle :MessageHandle,IMessageHandle
	{
		public IDTMessageHandle(IContainer container) : base(container)
		{

		}

		public override void AnalysisHandle(Queue<DataPack> qdataPacks, byte[] data, int length)
		{


			if (data == null || length < 7)
			{
				//ReplyBuffer = ErrorReply((int)SocketErrorCode.BadRequest);
				logger.Error($"IDTMessageHandle.AnalysisHandle消息长度为{length}不符合要求!");
				return;
			}
			DataPack LastPack = null;
			int i=0;
			int datalen =0;
			//上一个包未完成的处理
			if (qdataPacks.Count > 0)
			{
				LastPack = qdataPacks.Peek();
				if (LastPack.Complete == false)
				{
					for (;i < length;i++)
					{
						if (data[i] == 0x3E && data[i + 1] == 0x24)
						{
							datalen = i + 1;
							byte[] buffer = new byte[i + 2];
							Array.Copy(data, 0, buffer, 0, buffer.Length);
							LastPack.ReceiveBuffer = LastPack.ReceiveBuffer.Concat(buffer).ToArray();//拼接上一次剩余的包,已经完成读取每个数据包长度
							LastPack.Length = LastPack.ReceiveBuffer.Length;
							SetDataPack(LastPack);
							break;
						}
					}
				}
			}

			//装包
			for (i=datalen;i < length; i++)
			{
				if (data[i] == 0x3E && data[i + 1] == 0x24)
				{
					DataPack dataPack = new DataPack();
					dataPack.ReceiveBuffer = new byte[i + 2];
					dataPack.Length = i + 2;
					Array.Copy(data, 0, dataPack.ReceiveBuffer, 0, dataPack.Length);
					SetDataPack(dataPack);
					qdataPacks.Enqueue(dataPack);
					datalen = i + 1;
				}
			}

			if (datalen+1< length)
			{

				DataPack dataPack = new DataPack();
				dataPack.Length = length - datalen;
				dataPack.ReceiveBuffer = new byte[dataPack.Length];
				Array.Copy(data, 0, dataPack.ReceiveBuffer, 0, dataPack.Length);
				qdataPacks.Enqueue(dataPack);
			}
		}

		public override void Handle(IContext context)
		{
			 base.Handle(context);
		}

		public override void Handled(IContext context)
		{
			logger.Info($"commandid={context.CurrentPack.CommandID} 处理完成!");
		}



	}
}
